const base64ToSrc = require("../../utils/base64src.js");
const validate = require('../../utils/validate')
const authServices = require('../../services/auth')
const common = require('../../utils/common')

Page({
  data: {
    codeImgUrl: '',
    code: '',
    isNextEnable: false,
    phone: '',
  },
  onLoad: function (options) {
    this.initData(options);
  },
  //初始化数据
  initData: function (options) {
    let tmpBase64Data = options.imgBase64Data;
    this.handlerBase64Img(tmpBase64Data)
    this.setData({
      phone: options.phone
    })
  },
  handlerBase64Img: function (base64) {
    base64ToSrc.imageUrlWithBase64src(base64).then((res) => {
      this.setData({ codeImgUrl: res });
    });
  },
  checkCanSubmit: function () {
    const code = this.data.code
    let isNextEnable = !!code
    this.setData({
      isNextEnable
    })
    return isNextEnable
  },
  //输入图形验证码
  bindCodeInput: function (e) {
    this.setData({
      code: e.detail.value
    }, this.checkCanSubmit);
  },

  //下一步
  onNext: function () {
    //调用方法，返回上一页
    const pages = getCurrentPages();
    const prePage = pages[pages.length - 2];
    const e = {
      detail: {
        value: this.data.code
      }
    };
    prePage.validateCode(e);
    //返回
    wx.navigateBack({});
  },
  //获取验证码
  onGetCode: function (e) {
    //手机号
    if (!this.data.phone) {
      common.showToast('手机号码不能为空!');
      return
    }
    if (!validate.isPhone(this.data.phone)) {
      common.showToast('请输入正确的手机号!');
      return
    }
    //请求获取手机验证码
    this.requestToGetLoginVerfication(this.data.phone);
  },

  //请求获取手机验证码
  requestToGetLoginVerfication: function (phone) {
    let data = {
      mobile: phone,
      imgCode: this.data.code
    }
    authServices.getVerficationCode(data).then(res => {
      if (res.code == 600) {
        this.handlerBase64Img(res.data)
      } else {
        wx.navigateBack({});
      }
    }).catch(err => {
      common.log(err);
    });
  },
})